# coding: utf-8


'''
success  68.101.57.233:8080

ocr学习
http://san-yun.iteye.com/blog/1966165

机器学习
https://www.cnblogs.com/TTyb/p/6144740.html
https://www.zhihu.com/question/22479139
https://kechuang.org/t/25352

去噪
http://blog.csdn.net/xjay_cc/article/details/51883383
http://www.cnblogs.com/marryZhan/archive/2010/05/11/2213952.html
http://www.cnblogs.com/kingthy/archive/2008/08/06/1262475.html

github
https://github.com/Kagami/chaptcha
https://github.com/hanc00l/captcha-python-test
https://github.com/ya-mouse/opencv-captcha
https://github.com/00nanhai/captchacker2

opencv
http://blog.csdn.net/xieyi4650/article/details/51361675
'''

import os
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageEnhance
from handler.image import *
import sys
reload(sys)
sys.setdefaultencoding('utf-8')


#临时变量
minLineLength = 20

#全局变量
minLINELENGTH = 20
max_value = 100
window_name = "HoughLines Demo"
trackbar_value = "minLineLength"

import math
#两个回调函数


def main():
    # image_directory = os.path.join(os.getcwd(), 'pic')
    # image_name = '4.jpg'
    # image_path = os.path.join(image_directory, image_name)
    image_url = 'http://service.cpic.com.cn/common/generateCaptcha?1516336380426'
    image = download_to_image(image_url)
    image = image.convert('L')
    # image = image.point(lambda x: 255 if x > 200 or x == 0 else x)
    # image = image.point(lambda x: 0 if x < 255 else 255, "1")
    image = image.point(lambda x: 255 if x > 230 else x)
    image = image.point(lambda x: 0 if x < 255 else 255, "1")
    width, height = image.size
    # arr = np.zeros((height, width), np.float)
    # imarr = np.array(image, dtype=np.float)
    # print(imarr)
    # arr = arr + imarr / (1000 * 2)
    # arr = np.array(np.round(arr), dtype=np.uint8)
    # image = Image.fromarray(arr, mode="L")

    image.show()
    exit()
    # image.save(image_path)
    # image.show()
    # 图像二值化
    # enhancer = ImageEnhance.Sharpness(image)
    # enhancer = ImageEnhance.Contrast(image)
    # enhancer = ImageEnhance.Brightness(image)
    # image = enhancer.enhance(2)
    # image = image.convert('1')
    # data = image.getdata()
    # w, h = image.size
    img = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
    kernel = np.uint8(np.zeros((3, 3)))
    for x in range(3):
        kernel[x, 2] = 1
        kernel[2, x] = 1
    # 腐蚀图像
    eroded = cv2.erode(img, kernel)
    # 膨胀图像
    dilated = cv2.dilate(img, kernel)
    # 将两幅图像相减获得边，第一个参数是膨胀后的图像，第二个参数是腐蚀后的图像
    result = cv2.absdiff(dilated, eroded)
    # 取反
    x, y = 0, 0
    width, height = result.shape[0], result.shape[1]
    while x < width:
        y = 0
        while y < height:
            result[x][y] = 255 - result[x][y]
            y += 1
        x += 1
    image.save("/home/yehun/image.jpg")
    cv2.imwrite("/home/yehun/eroded.jpg", eroded)
    cv2.imwrite("/home/yehun/dilated.jpg", dilated)
    cv2.imwrite("/home/yehun/result.jpg", result)
    # image = binarizing(image, 150)
    # image.show()
    # clear_noise(image)
    # data = image.getdata()
    # image.show()
    image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
    code = image_to_string(image)
    print('code={0}'.format(code))
    # image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    # kernel = np.ones((1, 1), np.uint8)
    # erosion = cv2.erode(img, kernel)
    # gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)
    # cv2.imshow("OpenCV", gradient)
    # cv2.waitKey()


if __name__ == '__main__':
    main()
    # import requests
    # response = requests.post('https://channel.kxqianbao.com/yuyin/index.php?g=Api&m=ToCode&a=get_code', {
    #     'token': '96d5bded370406e1764a58d93feede7a',
    #     'pid': 7,
    #     'tit': '明明',
    #     'con': '向你发出了一个口令红包',
    #     'page': 'pages/recordDetails/recordDetails'
    # })
    # print(response.text)